/**
 * 
 * 起迪科技 Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */
package cn.qidisoft.edu.hzjt.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.util.StringUtils;
import cn.qidisoft.core.web.customargument.bind.annotation.IfNeedLogin;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.model.Priority;
import cn.qidisoft.edu.hzjt.model.RecommendStudent;
import cn.qidisoft.edu.hzjt.model.Student;
import cn.qidisoft.edu.hzjt.model.StudentClass;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.service.ICommonService;
import cn.qidisoft.edu.hzjt.service.IRecommendStudentService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * @author hxq
 * @version $Id: CommonController.java, v 0.1 2018年10月24日 下午4:55:00 hxq Exp $
 */
@Controller
@RequestMapping("common")
@IfNeedLogin(needLogin = false)
public class CommonController {
  protected static final LoggerAdapter LOGGER =
      LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);

  @Autowired
  private ICommonService commonService;

  @Autowired
  private IRecommendStudentService recommendStudentService;



  /**
   * 根据用户ID获取用户信息
   * 
   * @param request
   * @param response
   * @param uid
   * @param type
   * @return
   */
  @RequestMapping(value = "/userInfo")
  public Object getUserInfo(HttpServletRequest request, HttpServletResponse response,
      @RequestParam(value = "uid") Integer uid, @RequestParam(value = "type") String type,
      ModelMap model) {
    try {
      if (!StringUtils.isNullValue(type) && "t".equals(type)) {
        UserEmployee userEmployee = getUserEmployee(uid, commonService);
        return userEmployee;
      } else if (!StringUtils.isNullValue(type) && "s".equals(type)) {
        Student student = getStudentEmployee(uid, commonService);
        return student;
      } else {
        return null;
      }
    } catch (Exception e) {
      LOGGER.error("获得用户信息 getUserInfo [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
  }

  /**
   * 获得教师用户信息
   * 
   * @param uid
   * @param userService
   * @return
   */
  @SysLogger(description = "用户教职工公用信息", moduleName = "公共信息", method = "获得用户对应教职工信息")
  private static UserEmployee getUserEmployee(Integer uid, ICommonService commonService) {
    UserEmployee user = new UserEmployee();
    user.setUid(uid);
    UserEmployee userList = commonService.queryUserByEmployee(user);
    return userList;
  }

  @SysLogger(description = "用户学生公用信息", moduleName = "公共信息", method = "获得用户学生信息")
  private static Student getStudentEmployee(Integer uid, ICommonService commonService) {
    Student student = new Student();
    student.setXsid(uid);
    return commonService.queryStudentByEmployee(student);
  }

  /**
   * 获得教师权限信息
   * 
   * @param request
   * @param response
   * @param uid
   * @return
   */
  @RequestMapping(value = "/userRoleInfo")
  public List<Priority> getUserRoleInfo(HttpServletRequest request, HttpServletResponse response,
      @RequestParam(value = "uid") Integer uid) {
    try {
      UserEmployee priority = new UserEmployee();
      priority.setUid(uid);
      return commonService.queryUserByPriority(priority);
    } catch (Exception e) {
      LOGGER.error("获得用户权限信息 getUserRoleInfo [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
    }
    return null;
  }

  /**
   * 通过年级和专业获得班级信息
   * 
   * @param request
   * @param response
   * @param njid
   * @param zyid
   * @return
   */
  @RequestMapping(value = "/getGradeSpecialityByClass")
  public @ResponseBody String getSpecialityIdByClass(HttpServletRequest request,
      HttpServletResponse response, @RequestParam(value = "njid") Integer njid,
      @RequestParam(value = "zyid") Integer zyid, @RequestParam(value = "bzrid") Integer bzrid) {
    response.setContentType("text/html;charset=utf-8");
    try {
      if (njid == null && zyid == null) {
        return JSON.toJSONString(new ArrayList<StudentClass>());
      } else {
        Student student = new Student();
        student.setNjid(njid);
        student.setZyid(zyid);
        if (bzrid.intValue() != -1) {
          student.setBzrid(bzrid);
        }
        List<StudentClass> classList = commonService.queryGradeSpecialtyByClass(student);
        return JSON.toJSONString(classList);
      }
    } catch (Exception e) {
      LOGGER.error(
          "获得班级信息 getSpecialityIdByClass [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      return "error/error";
    }
  }

  /**
   * 获取符合项的学生信息
   * 
   * @param request
   * @param response
   * @param njid
   * @param zyid
   * @return
   */
  @RequestMapping(value = "/getSemesterByStudentConductList")
  public @ResponseBody String getSemesterByStudentConductList(HttpServletRequest request,
      HttpServletResponse response, @RequestParam(value = "pytype") Integer pytype,
      @RequestParam(value = "semid") Integer semid, ModelMap model) {
    response.setContentType("text/html;charset=utf-8");
    try {
      if (pytype == null || semid == null) {
        return JSON.toJSONString(new ArrayList<Student>());
      } else {
        Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
        String ismanager = request.getParameter("ismanager");
        String tjid = request.getParameter("tjid");
        String p21 = request.getParameter("p21");
        String p22 = request.getParameter("p22");
        String p = request.getParameter("p");
        Student student = new Student();
        student.setPytype(pytype);
        student.setYxid(semid);
        student.setIsmanager(new Integer(ismanager));
        if (!StringUtils.isNullValue(tjid)) {
          student.setTjid(Integer.parseInt(tjid));
        }
        if (loginType == 2) { // 老师
          UserEmployee userEmployee =
              (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
          student.setBzrid(userEmployee.getEmid());
        }
        switch (pytype) {
          case 1: // 行为达标生
            if (!StringUtils.isNullValue(p21) && p21.equals("1")) {
              student.setCxgrades(new String[] {"优"});
            } else {
              student.setCxgrades(new String[] {"合格"});
            }
            break;
          case 2: // 好学生
            if (!StringUtils.isNullValue(p21) && p21.equals("1")) {
              student.setCxgrades(new String[] {"优"});
            } else {
              student.setCxgrades(new String[] {"良", "优"});
            }
            break;
          case 3: // 三好学生
            student.setCxgrades(new String[] {"优"});
            break;
          case 4: // 优秀班干部
            student.setCxgrades(new String[] {"优"});
            break;
          case 5: // 技能特长生
            switch (p) {
              case "1":
                student.setCxgrades(new String[] {"合格"});
                break;
              case "2":
                student.setCxgrades(new String[] {"良", "优"});
                break;
              case "3":
                student.setCxgrades(new String[] {"优"});
                break;
              default:
                student.setCxgrades(null);
                break;
            }
            break;
          case 6: // 优秀班干部和技能特长生
            student.setCxgrades(new String[] {"优"});
            break;
          default:
            student.setCxgrades(null);
            break;
        }
        List<Student> studentList = commonService.querySemesterByStudentConductList(student);
        return JSON.toJSONString(studentList);
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("获得符合项的推荐学生信息 getSemesterByStudentConductList [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
  }

  /**
   * 获取符合条件选中学生信息
   * 
   * @param request
   * @param response
   * @param njid
   * @param zyid
   * @return
   */
  @RequestMapping(value = "/getSemesterStudentScoreConductList")
  public @ResponseBody String getSemesterStudentScoreConductList(HttpServletRequest request,
      HttpServletResponse response, @RequestParam(value = "xsid") Integer xsid,
      @RequestParam(value = "semid") Integer semid, ModelMap model) {
    response.setContentType("text/html;charset=utf-8");
    try {
      if (xsid == null || semid == null) {
        return JSON.toJSONString(new ArrayList<Student>());
      } else {
        Student student = new Student();
        student.setXsid(xsid);
        student.setYxid(semid);
        List<Student> studentList = commonService.querySemesterStudentScoreConductList(student);
        return JSON.toJSONString(studentList);
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("获得符合项的推荐学生信息 getSemesterByStudentConductList [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
  }

  /**
   * 通过学年获得学生评定成绩信息
   * 
   * @param request
   * @param response
   * @param xsid
   * @param xnd
   * @return
   */
  @RequestMapping(value = "/getRecommendStudentScoreConductList")
  public @ResponseBody String getRecommendStudentScoreConductList(HttpServletRequest request,
      HttpServletResponse response, @RequestParam(value = "xsid") Integer xsid,
      @RequestParam(value = "xnd") Integer xnd, ModelMap model) {
    response.setContentType("text/html;charset=utf-8");
    try {
      if (xsid == null || xnd == null) {
        return JSON.toJSONString(new ArrayList<Student>());
      } else {
        Student student = new Student();
        student.setXsid(xsid);
        student.setXnd(xnd);
        List<Student> studentList = commonService.querySemesterStudentScoreConductList(student);
        return JSON.toJSONString(studentList);
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("获得符合项的推荐学生信息 getSemesterByStudentConductList [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
  }

  /**
   * 获取符合条件选中学生信息
   * 
   * @param request
   * @param response
   * @param njid
   * @param zyid
   * @return
   */
  @RequestMapping(value = "/getReCommendStudentScoreConductCount")
  public @ResponseBody String getReCommendStudentScoreConductCount(HttpServletRequest request,
      HttpServletResponse response, @RequestParam(value = "bjid") Integer bjid,
      @RequestParam(value = "semid") Integer semid, @RequestParam(value = "pxxm1") String pxxm1,
      ModelMap model) {
    response.setContentType("text/html;charset=utf-8");
    try {
      if (bjid == null && semid == null) {
        return null;
      } else {
        String p21 = request.getParameter("p21");
        String p22 = request.getParameter("p22");
        if (!StringUtils.isNullValue(pxxm1) && !StringUtils.isNullValue(p21)
            && !StringUtils.isNullValue(p22)) {
          return null;
        }
        Student student = new Student();
        student.setBjid(bjid);
        int classStudentCount = commonService.queryClassStudentCount(student);
        RecommendStudent recommendStudent = new RecommendStudent();
        recommendStudent.setBjid(bjid);
        recommendStudent.setSemid(semid);
        // recommendStudent.setPxxm1(pxxm1);

        int recommendStudentCount = 0;
        String message = "";
        if (!StringUtils.isNullValue(p21) && StringUtils.isNullValue(p22)) { // 符合三好学生标准
          recommendStudent.setPxxm2(p21);
          recommendStudent.setPxxm1(null);
          recommendStudentCount =
              recommendStudentService.queryRecommendStudentClassCount(recommendStudent);
          if (recommendStudentCount >= 1) {
            // message = Constant.PXXM_TYPE4 + "项目推荐学生数不能超过1人";
            message = "5";
            return message;
          } else {
            recommendStudent.setPxxm2(null);
            recommendStudent.setPxxm1(pxxm1);
            recommendStudentCount =
                recommendStudentService.queryRecommendStudentClassCount(recommendStudent);
            message = verfityPXXM(pxxm1, recommendStudentCount, classStudentCount);
            return message;
          }
        } else if (StringUtils.isNullValue(p21) && !StringUtils.isNullValue(p22)) { // 技能特长生
          recommendStudent.setPxxm2(p22);
          recommendStudent.setPxxm1(null);
          recommendStudentCount =
              recommendStudentService.queryRecommendStudentClassCount(recommendStudent);
          if (recommendStudentCount >= 2) {
            // message = Constant.PXXM_TYPE5 + "项目推荐学生数不能超过2人";
            message = "6";
            return message;
          } else {
            recommendStudent.setPxxm2(null);
            recommendStudent.setPxxm1(pxxm1);
            recommendStudentCount =
                recommendStudentService.queryRecommendStudentClassCount(recommendStudent);
            message = verfityPXXM(pxxm1, recommendStudentCount, classStudentCount);
            return message;
          }
        } else if (!StringUtils.isNullValue(p21) && !StringUtils.isNullValue(p22)) { // 两者都不为空
          recommendStudent.setPxxm2(p21);
          recommendStudent.setPxxm1(null);
          recommendStudentCount =
              recommendStudentService.queryRecommendStudentClassCount(recommendStudent);
          if (recommendStudentCount >= 1) {
            // message = Constant.PXXM_TYPE4 + "项目推荐学生数不能超过1人";
            message = "5";
            return message;
          } else {
            recommendStudent.setPxxm2(p22);
            recommendStudent.setPxxm1(null);
            recommendStudentCount =
                recommendStudentService.queryRecommendStudentClassCount(recommendStudent);
            if (recommendStudentCount >= 2) {
              // message = Constant.PXXM_TYPE5 + "项目推荐学生数不能超过2人";
              message = "6";
              return message;
            } else {
              recommendStudent.setPxxm2(null);
              recommendStudent.setPxxm1(pxxm1);
              recommendStudentCount =
                  recommendStudentService.queryRecommendStudentClassCount(recommendStudent);
              message = verfityPXXM(pxxm1, recommendStudentCount, classStudentCount);
              return message;
            }
          }

        } else {
          recommendStudent.setPxxm2(null);
          recommendStudent.setPxxm1(pxxm1);
          recommendStudentCount =
              recommendStudentService.queryRecommendStudentClassCount(recommendStudent);
          message = verfityPXXM(pxxm1, recommendStudentCount, classStudentCount);
          return message;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("获得符合项的推荐学生信息 getReCommendStudentScoreConductCount [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
  }

  /**
   * 验证评审项目
   * 
   * @param pxxm
   * @return
   */
  private static String verfityPXXM(String pxxm, int recommendStudentCount, int classStudentCount) {
    String message = null;
    switch (pxxm) {
      case Constant.PXXM_TYPE1:
        if ((recommendStudentCount < classStudentCount * Constant.STUDENT_SHXS)) {
          message = "1";
        } else {
          // message = Constant.PXXM_TYPE1 + "项目推荐学生数不能超过班级总人数的" + Constant.STUDENT_SHXS * 100 +
          // "%";
          message = "2";
        }
        break;
      case Constant.PXXM_TYPE2:
        if ((recommendStudentCount < classStudentCount * Constant.STUDENT_HXS)) {
          message = "1";
        } else {
          // message = Constant.PXXM_TYPE2 + "项目推荐学生数不能超过班级总人数的" + Constant.STUDENT_HXS * 100 + "%";
          message = "3";
        }
        break;
      case Constant.PXXM_TYPE3:
        if ((recommendStudentCount < classStudentCount * Constant.STUDENT_XWDB)) {
          message = "1";
        } else {
          // message = Constant.PXXM_TYPE3 + "项目 推荐学生数不能超过班级总人数的" + Constant.STUDENT_XWDB * 100 +
          // "%";
          message = "4";
        }
        break;
      default:
        break;
    }
    return message;
  }

  /**
   * IO流读取图片 by:long
   * 
   * @return
   */
  @RequestMapping(value = "/IoReadImage", method = RequestMethod.GET)
  public String IoReadImage(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    ServletOutputStream out = null;
    FileInputStream ips = null;
    try {
      // 获取图片存放路径
      String imgName = request.getParameter("imgName");
      String imgPath = Constant.UPLOADPATH + File.separator + imgName;
      ips = new FileInputStream(new File(imgPath));
      response.setContentType("multipart/form-data");
      out = response.getOutputStream();
      // 读取文件流
      int len = 0;
      byte[] buffer = new byte[1024 * 10];
      while ((len = ips.read(buffer)) != -1) {
        out.write(buffer, 0, len);
      }
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      out.close();
      ips.close();
    }
    return null;
  }



}
